package com.xuecheng.media.infrastructure.util;

import com.j256.simplemagic.ContentInfo;
import com.j256.simplemagic.ContentInfoUtil;
import com.xuecheng.base.exception.XueChengPlusException;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.http.MediaType;

import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

/**
 * @Author: LiJunXi
 * @Description:
 * @Date: 2024-08-04  14:49
 */
public class UploadUtil {

    /**
     * 获取默认上传的文件夹
     * @return
     */
    public static String getDefaultAbsolutePath() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(new Date()).replace("-", "/") + "/";
    }

    /**
     * 获取文件md5值
     * @param file
     * @return
     */
    public static String getFileMd5(File file) {
        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            return DigestUtils.md5Hex(fileInputStream);
        } catch (Exception e){
            throw new XueChengPlusException("文件md5值获取出错");
        }
    }

    /**
     * 获取文件后缀
     * @param filename
     * @return
     */
    public static String getExtension(String filename) {
        return filename.split("\\.")[1];
    }

    /**
     * 根据扩展名取出mimeType
     * @param extension
     * @return
     */
    public static String getMimeType(String extension) {
        if (Objects.isNull(extension)){
            extension = "";
        }
        ContentInfo extensionMatch = ContentInfoUtil.findExtensionMatch(extension);
        String mimeType = MediaType.APPLICATION_OCTET_STREAM_VALUE;  // 通用mimeType，字节流
        if (Objects.nonNull(extensionMatch)){
            mimeType = extensionMatch.getMimeType();
        }
        return mimeType;
    }

    /**
     * 获取分片文件总路径
     * @param fileMd5
     * @return
     */
    public static String getChunkPath(String fileMd5) {
        return "chunk_temp/" + fileMd5.substring(0, 1) + "/" +
                fileMd5.substring(1, 2) + "/" + fileMd5 + "/" + "chunk" + "/";
    }

    /**
     * 获取某个分片的具体路径
     * @param fileMd5
     * @return
     */
    public static String getChunkObjPath(String fileMd5, Integer chunk){
        return UploadUtil.getChunkPath(fileMd5) + chunk;
    }

    public static String getFileName(String objectName) {
        return objectName.split("/")[1];
    }
}
